{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "import argparse\n",
    "import sys\n",
    "import os\n",
    "os.chdir(\"E:\\pythonstudy\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting MNIST_data/train-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data/train-labels-idx1-ubyte.gz\n",
      "Extracting MNIST_data/t10k-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data/t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "#载入MNIST数据集，创建默认的Interactive Session。\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "import tensorflow as tf\n",
    "mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n",
    "sess = tf.InteractiveSession()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#初始化函数\n",
    "def weight_variable(shape):\n",
    "    \n",
    "    initial = tf.truncated_normal(shape, stddev=0.1)\n",
    "    return tf.Variable(initial)\n",
    "  \n",
    "def bias_variable(shape):\n",
    "    initial = tf.constant(0.1, shape=shape)\n",
    "    return tf.Variable(initial)\n",
    "  \n",
    "def conv2d(x, W):\n",
    "    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n",
    "  \n",
    "def max_pool_2x2(x):\n",
    "    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "x_image = tf.reshape(x, [-1,28,28,1])\n",
    "learning_rate=0.001"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "#定义第一个卷积层。\n",
    "#初始化各个参数，其中[6,6,1,32]表示kemel size为6*6，1个颜色通道，kemel size数量为32\n",
    "W_conv1 = weight_variable([6, 6, 1, 32])\n",
    "b_conv1 = bias_variable([32])\n",
    "h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\n",
    "h_pool1 = max_pool_2x2(h_conv1)#池化\n",
    "#定义第二个卷积层。\n",
    "W_conv2 = weight_variable([3, 3, 32, 64])\n",
    "b_conv2 = bias_variable([64])\n",
    "h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n",
    "h_pool2 = max_pool_2x2(h_conv2)\n",
    "  \n",
    "W_fc1 = weight_variable([7 * 7 * 64, 1024])\n",
    "b_fc1 = bias_variable([1024])\n",
    "h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])\n",
    "h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n",
    "\n",
    "#输出\n",
    "W_fc2 = weight_variable([1024, 10])\n",
    "b_fc2 = bias_variable([10])\n",
    "y_conv=tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2)\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "#定义损失函数cross_entropy，这里选择Adam优化器。\n",
    "cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))\n",
    "regularizer=tf.contrib.layers.l2_regularizer(0.0001)\n",
    "regularization=regularizer(W_fc1)+regularizer(W_fc2)#正则化\n",
    "cross_entropy+=regularization\n",
    "\n",
    "train_step = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy)#在此处设置学习率\n",
    "#继续定义评测准确率操作。\n",
    "correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 0, training accuracy 0.1\n",
      "step 200, training accuracy 0.88\n",
      "step 400, training accuracy 0.9\n",
      "step 600, training accuracy 0.98\n",
      "step 800, training accuracy 0.98\n",
      "test accuracy 0.9813\n"
     ]
    }
   ],
   "source": [
    "# #开始训练过程。\n",
    "sess.run(tf.global_variables_initializer())\n",
    "\n",
    "for i in range(1000):\n",
    "    \n",
    "    batch = mnist.train.next_batch(50)\n",
    "    trainingInputs = batch[0]\n",
    "    trainingLabels = batch[1]\n",
    "    if i%200==0:\n",
    "        trainaccuracy =accuracy.eval(session=sess,feed_dict={x:trainingInputs,y_:trainingLabels,keep_prob: 0.5})\n",
    "        print(\"step %d, training accuracy %g\"%(i, trainaccuracy))\n",
    "    train_step.run(session=sess,feed_dict={x:trainingInputs,y_:trainingLabels,keep_prob: 0.5})\n",
    "\n",
    "print(\"test accuracy %g\"%accuracy.eval(feed_dict={ x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
